package com.otp.service.impl;

import com.otp.exception.BusinessException;
import com.otp.pojo.entity.Paper;
import com.otp.pojo.entity.PaperSubmission;
import com.otp.pojo.entity.Question;
import com.otp.pojo.request.paper.PaperSubmissionGradeRequest;
import com.otp.repository.PaperRepository;
import com.otp.repository.PaperSubmissionRepository;
import com.otp.repository.QuestionRepository;
import com.otp.service.PaperSubmissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class PaperSubmissionServiceImpl implements PaperSubmissionService {

    @Autowired
    private PaperRepository paperRepository;
    @Autowired
    private QuestionRepository questionRepository;
    @Autowired
    private PaperSubmissionRepository paperSubmissionRepository;

    @Override
    public PaperSubmission grade(PaperSubmissionGradeRequest request) {
        PaperSubmission submission = paperSubmissionRepository.findById(request.getSubmissionId())
                .orElseThrow(() -> new BusinessException("试卷提交记录不存在"));
        Paper paper = paperRepository.findById(submission.getPaperId())
                .orElseThrow(() -> new BusinessException("试卷不存在"));

        // 获取试卷中的试题
        List<Question> questions = questionRepository.findAllById(paper.getQuestionIds());
        double score = 0.0;
        double scorePerQuestion = 100.0 / questions.size(); // 假设每题均分 100 分

        // 自动评分单选题和判断题
        for (Question question : questions) {
            String studentAnswer = submission.getAnswers().get(question.getId());
            String correctAnswer = question.getAnswer();

            if ("SINGLE_CHOICE".equals(question.getType()) || "TRUE_FALSE".equals(question.getType())) {
                if (studentAnswer != null && studentAnswer.equals(correctAnswer)) {
                    score += scorePerQuestion;
                }
            }
        }

        // 手动评分大题
        for (Map.Entry<Long, String> entry : request.getTextQuestionScores().entrySet()) {
            Long questionId = entry.getKey();
            Question question = questions.stream()
                    .filter(q -> q.getId().equals(questionId) && "TEXT".equals(q.getType()))
                    .findFirst()
                    .orElseThrow(() -> new BusinessException("大题 ID " + questionId + " 无效或非大题"));
            try {
                double textScore = Double.parseDouble(entry.getValue());
                if (textScore < 0 || textScore > scorePerQuestion) {
                    throw new BusinessException("大题评分必须在 0 到 " + scorePerQuestion + " 之间");
                }
                score += textScore;
            } catch (NumberFormatException e) {
                throw new BusinessException("大题评分格式错误");
            }
        }

        submission.setScore(score);
        submission.setStatus("GRADED");
        return paperSubmissionRepository.save(submission);
    }

    @Override
    public PaperSubmission getSubmissionById(Long id) {
        return paperSubmissionRepository.findById(id)
                .orElseThrow(() -> new BusinessException("试卷提交记录不存在"));
    }

    @Override
    public List<PaperSubmission> listSubmissions() {
        return paperSubmissionRepository.findAll();
    }

    @Override
    public List<PaperSubmission> listSubmissionsByPaperId(Long paperId) {
        return paperSubmissionRepository.findByPaperId(paperId);
    }

    @Override
    public List<PaperSubmission> listSubmissionsByStudentId(Long studentId) {
        return paperSubmissionRepository.findByStudentId(studentId);
    }

    @Override
    public List<PaperSubmission> listSubmissionsByStatus(String status) {
        return paperSubmissionRepository.findByStatus(status);
    }
}
